import { ConfigEnv, UserConfigExport, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
console.log('__dirname', __dirname)
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { viteMockServe } from 'vite-plugin-mock'
// 浏览器开发工具
// import VueDevTools from 'vite-plugin-vue-devtools'

// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  // console.log('loadEnv', loadEnv(mode, process.cwd()))
  // 当前环境自定义变量
  const curEnvVar = loadEnv(mode, process.cwd())
  return {
    root: process.cwd(), //项目根目录（index.html 文件所在的位置） 默认： process.cwd()
    // publicDir: path.resolve(__dirname, './dist'), //默认'public'  作为静态资源服务的文件夹  (打包public文件夹会没有，里面得东西会直接编译在dist文件下)
    assetsInclude: path.resolve(__dirname, './src/assets'), // 静态资源处理
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src')
      },
      // import省略后缀
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },
    plugins: [
      vue(),
      // VueDevTools(),
      // 自动导入api，无需手动import
      AutoImport({
        imports: ['vue'],
        // element-plus按需引入
        resolvers: [ElementPlusResolver()],
        // 处理auto-import与eslint冲突，如去掉import之后ref未定义
        eslintrc: {
          enabled: true,
          filepath: './.eslintrc-auto-import.json',
          globalsPropValue: true
        },
        // 将 d.ts 文件生成在 src/types/auto-import 目录下
        dts: 'src/types/auto-import/auto-imports.d.ts'
      }),
      Components({
        // 指定组件位置，默认是src/components
        dirs: ['src/components'],
        // ui库解析器
        resolvers: [ElementPlusResolver()],
        extensions: ['vue'],
        // 配置文件生成位置src/types/auto-import
        dts: 'src/types/auto-import/components.d.ts'
      }),
      // svgIcons插件
      createSvgIconsPlugin({
        // Specify the icon folder to be cached
        iconDirs: [path.resolve(process.cwd(), 'src/assets/svgs')],
        // Specify symbolId format
        symbolId: 'icon-[dir]-[name]',
        customDomId: '__svg__icons__dom__'
      }),
      viteMockServe({
        // default
        mockPath: 'src/mock',
        // 开发环境才启动mock
        // 硅谷官方的login api不能用 可能线上还需mock
        localEnabled: mode === 'development' || mode === 'production'
      })
    ],
    // css全局变量
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData: '@import "./src/styles/var.scss";'
        }
      }
    },
    server: {
      open: true,

      // swagger文档
      // 商品：http://139.198.104.58:8209/swagger-ui.html eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJSSkzJzcxT0lFKrShQsjI0MzQzMTK1NDGvBQApMebnIAAAAA.UG2Qj7F7ASMLBugNG67-wKs0Un6ORrneMkSdio0rKhX0o-fd6BC24T1gCzfVVtsNERPzs4Sjwz8JOyPfLazUSA
      // 用户：http://139.198.104.58:8212/swagger-ui.html#/
      // http://114.115.179.162:8022/prod-api/swagger-ui.html
      proxy: {
        // [curEnvVar.VITE_APP_BASE_API]: {
        //   target: 'http://sph-api.atguigu.cn',
        //   changeOrigin: true,
        //   rewrite: (path) => {
        //     const apiReg = new RegExp(`^\${curEnvVar.VITE_APP_BASE_API}`)
        //     console.log('apiReg', apiReg)
        //     return path.replace(apiReg, '')
        //   }
        // }
        // 用户api地址转发
        [`${curEnvVar.VITE_APP_BASE_API}/admin/acl`]: {
          target: 'http://139.198.104.58:8212',
          changeOrigin: true,
          rewrite: (path) =>
            path.replace(/^\/dev-api\/admin\/acl/, '/admin/acl')
        },
        // 产品api地址转发
        [`${curEnvVar.VITE_APP_BASE_API}/admin/product`]: {
          // target: 'http://139.198.104.58:8209',
          target: 'http://39.98.123.211:8510',
          changeOrigin: true,
          rewrite: (path) =>
            path.replace(/^\/dev-api\/admin\/product/, '/admin/product')
        }
      }
    }
  }
}
